<template>
    <a-layout style="min-height: 100vh">
        <a-layout :style="{
            backgroundImage: 'url(' + backGroundImg + ')',
            backgroundRepeat: 'no-repeat', backgroundSize: '1600px 200px'
        }" style="background-color: #fff;">

            <a-layout-header style="background: transparent; padding: 0; margin-bottom: 20px;">
                <div style="display: flex;">
                    <div>
                        <img src="@/assets/logo-no-background.png" style="height: 60px;" @click="$router.push('/homepage_demo' + '?randomId=' + Math.random())" />
                    </div>
                    <div v-if="!login" style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-button style="background: transparent; color: white" @click="onLoginShow">
                            <template #icon><user-outlined style="color: white"/></template>
                            登录
                        </a-button>
                    </div>
                    <div v-else style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-dropdown>
                            <a-button style="background: transparent; color: white">
                                <user-outlined style="color: white"/>
                                {{ $store.state.username }}
                                <DownOutlined />
                            </a-button>
                            <template #overlay>
                                <a-menu @click="onMenuClick">
                                    <a-menu-item key="center">
                                        <span style="display: flex; justify-content: center;">个人中心</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="favorite">
                                        <span style="display: flex; justify-content: center;">我的收藏</span>
                                    </a-menu-item>
                                    <a-menu-item key="interest">
                                        <span style="display: flex; justify-content: center;">我的关注</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="logout">
                                        <span style="display: flex; justify-content: center;">退出登录</span>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                </div>
                <hr class="custom-divider" />
            </a-layout-header>
            <a-layout-content>
                <div style="margin-top: 30px; margin-left: 420px">
                    <a-select defaultValue="title" :options="searchOptions" v-model:value="searchField" size="large" style="width: 80px" />
                    <a-input v-model:value="searchQuery" placeholder="请输入检索词" size="large" style="width: 580px; margin-left: 10px" />
                    <a-button type="primary" size="large" style="width: 100px; margin-left: 10px" @click="onSearch">
                        <template #icon><SearchOutlined /></template>
                        检索
                    </a-button>
                    <span style="color: white; margin-left: 10px ;cursor: pointer" @click="$router.push('/advancedSearch_demo')">高级检索></span>
                </div>
                <div style="margin-left: 300px; margin-top: 50px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; width: 1000px">
                        共找到 {{total}} 篇文章
                        <a-pagination v-model:current="currentPage" v-model:pageSize="pageSize" size="small"
                                      :total="total" show-size-changer show-quick-jumper @change="onPageChange" @showSizeChange="onShowSizeChange"/>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center; width: 1000px">
                        <div>
                            排序:
                            <a-button size="small" style="background-color: #4F4F4F; color: white">
                                <template #icon>
                                    <unordered-list-outlined :style="{color: 'white'}"/>
                                </template>
                                时效性
                            </a-button>
                            <a-button size="small" style="margin-left: 5px; background-color: white; color: #4F4F4F">
                                <template #icon>
                                    <unordered-list-outlined :style="{color: '#4F4F4F'}"/>
                                </template>
                                兴趣度
                            </a-button>
                        </div>
                        <div style="margin-top: 10px">
                            显示方式:
                            <a-button size="small" :class="paperShow === 'card' ? 'active' : 'inactive' " @click="onPaperShow">
                                <template #icon>
                                    <appstore-outlined :style="paperShow === 'card' ? 'color: white' : 'color: #4F4F4F'"/>
                                </template>
                                详细
                            </a-button>
                            <a-button size="small" style="margin-left: 5px;" :class="paperShow === 'list' ? 'active' : 'inactive' " @click="onPaperShow">
                                <template #icon>
                                    <menu-outlined :style="paperShow === 'list' ? 'color: white' : 'color: #4F4F4F'"/>
                                </template>
                                列表
                            </a-button>
                        </div>
                    </div>
                    <div v-if="paperShow==='card'" style="width: 1000px">
                        <a-list style="min-height: 350px;" :loading="loading" item-layout="vertical" size="large"
                                :data-source="data" :split="false">
                            <template #renderItem="{ item }">
                                <a-list-item>
                                    <a-card :loading="item.loading" style="border-width: 2px;">
                                        <p :style="{ color: item.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: item.isTitleHovered ? 'underline' : 'none' , fontSize: '20px', cursor: 'pointer'}"
                                           @mouseover="item.isTitleHovered = true"
                                           @mouseleave="item.isTitleHovered = false"
                                           @click="handleRead(item.paper_id)">
                                            <span v-html="highlightText(item.title, searchQuery)"></span>
                                        </p>
                                        <p style="color: #6C6C6C">
                                            <!-- 作者列表，可跳转至作者界面 -->
                                            作者:
                                            <template v-for=" (author, index) in item.authors"
                                                      :key="author.author_id">
                                                <u :style="{ color: author.isHovered ? '#6C6C6C' : '#0B0E47', textDecoration: author.isHovered ? 'underline' : 'none', cursor: 'pointer' }"
                                                   @mouseover="author.isHovered = true"
                                                   @mouseleave="author.isHovered = false"
                                                   @click="handleAuthor(author.author_id)">
                                                    {{ author.author_name }}
                                                </u>
                                                <span v-if="index < item.authors.length - 1">; </span>
                                            </template>
                                        </p>
                                       <a-typography-paragraph
                                                :ellipsis="ellipsis ? { rows: 3, expandable: true, symbol: '展开∨' } : false"
                                                :content="item.paper_abstract"
                                        />
                                        <p style="color: #6C6C6C; line-height: 2">
                                            所属学科:
                                            <template v-for=" (cat, index) in item.categories">
                                                    <span style="color: #0B0E47">{{ cat }}
                                                    </span>
                                                <span v-if="index < item.categories.length - 1">; </span>
                                            </template>
                                            <br/>
                                            <span v-if="item.journal_ref">
                                                    发表期刊: <span style="color: #0B0E47">{{ item.journal_ref }}</span>
                                                    <br/>
                                                </span>
                                            更新时间:
                                            <span style="color: #0B0E47">{{item.update_date}}</span>
                                        </p>
                                        <a-button v-if="item.favorite" :size="large" style="background-color: #EFEFEF" @click="handleFavorite(item.paper_id)">
                                            <template #icon>
                                                <star-filled :style="{color: '#FCCA00'}"/>
                                            </template>
                                            取消收藏
                                        </a-button>
                                        <a-button v-else :size="large" style="background-color: #EFEFEF" @click="handleFavorite(item.paper_id)">
                                            <template #icon>
                                                <StarOutlined />
                                            </template>
                                            加入收藏
                                        </a-button>
                                        <a-button :size="large" style="margin-left: 10px; background-color: #EFEFEF" @click="handlePDF(item.url)">
                                            <template #icon>
                                                <ReadOutlined />
                                            </template>
                                            在线阅读
                                        </a-button>
                                        <a-button :size="large" style="margin-left: 10px; background-color: #EFEFEF" @click="$router.push('/similar_paper?paper_id=' + item.paper_id)">
                                            <template #icon>
                                                <PaperClipOutlined />
                                            </template>
                                            查看相似论文
                                        </a-button>
                                    </a-card>
                                </a-list-item>
                            </template>
                        </a-list>
                    </div>
                    <div v-else style="margin-top: 10px; width: 1000px">
                        <a-table :columns="columns" :data-source="data" bordered :loading="loading" :pagination="false">
                            <template #bodyCell="{ column, text, record }">
                                <template v-if="column.dataIndex === 'title'">
                                    <span :style="{ color: record.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: record.isTitleHovered ? 'underline' : 'none' , fontSize: '16px', cursor: 'pointer'}"
                                          @mouseover="record.isTitleHovered = true"
                                          @mouseleave="record.isTitleHovered = false"
                                          @click="handleRead(record.paper_id)">
                                        {{ text }}
                                    </span>
                                </template>
                                <template v-else-if="column.dataIndex === 'author'">
                                    <template v-for=" (author, index) in record.authors"
                                              :key="author.author_id">
                                        <u :style="{ color: author.isHovered ? '#6C6C6C' : '#0B0E47', textDecoration: author.isHovered ? 'underline' : 'none', fontSize: '14px', cursor: 'pointer' }"
                                           @mouseover="author.isHovered = true"
                                           @mouseleave="author.isHovered = false"
                                           @click="handleAuthor(author.author_id)">
                                            {{ author.author_name }}
                                        </u>
                                        <span v-if="index < record.authors.length - 1">; </span>
                                    </template>
                                </template>
                                <template v-else-if="column.dataIndex === 'operations'">
                                    <span style="display: flex; justify-content: center; align-items: center;">
                                        <a-tooltip v-if="record.favorite" title="取消收藏">
                                            <star-filled style="color: #FCCA00; fontSize :20px" @click="handleFavorite(record.paper_id)"/>
                                        </a-tooltip>
                                        <a-tooltip v-else title="加入收藏">
                                            <StarOutlined style="fontSize :20px" @click="handleFavorite(record.paper_id)"/>
                                        </a-tooltip>
                                        <a-tooltip title="在线阅读">
                                            <ReadOutlined style="fontSize :20px; margin-left: 5px" @click="handlePDF(record.url)"/>
                                        </a-tooltip>
                                        <a-tooltip title="查看相似论文">
                                            <PaperClipOutlined style="fontSize :20px; margin-left: 5px" @click="$router.push('/similar_paper?paper_id=' + record.paper_id)"/>
                                        </a-tooltip>
                                    </span>
                                </template>
                                <template v-else>
                                    <span style="color: #0B0E47; font-size: 14px">{{ text }}</span>
                                </template>
                            </template>
                        </a-table>
                    </div>
                    <div style="display: flex; justify-content: center; align-items: center; width: 1000px; margin-bottom: 20px">
                        <a-pagination v-model:current="currentPage" show-quick-jumper :showSizeChanger="false" :total="total" @change="onPageChange" />
                    </div>
                </div>
                <a-modal v-model:visible="loginShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">欢迎登录</div>
                            <a-form
                                    :model="formState"
                                    name="normal_login"
                                    class="login-form"
                                    style="margin-top: 20px"
                                    @finish="onFinish"
                            >
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请输入账号' }]"
                                >
                                    <a-input v-model:value="formState.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请输入密码' }]"
                                >
                                    <a-input-password v-model:value="formState.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-form-item name="remember" no-style>
                                        <a-checkbox v-model:checked="formState.remember">自动登录</a-checkbox>
                                    </a-form-item>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-button :disabled="disabled" type="primary" html-type="submit" class="login-form-button" style="width: 100%">
                                        登录
                                    </a-button>
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px">
                                        <a href="">注册新用户</a>
                                        <a class="login-form-forgot" href="">忘记密码</a>
                                    </div>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
            </a-layout-content>
            <a-layout-footer style="background: #000; text-align: center">
                <p style="color:#fff">©{{ new Date().getFullYear() }} {{ systemTitle }}</p>
                <p style="color:#fff">
                    <a @click.prevent="$router.push('/about')">关于</a>&nbsp;|&nbsp;
                    <a>开发团队</a>&nbsp;|&nbsp;
                    <a href="https://gitee.com/shenyang-theone/theone-recsys">了解更多</a>
                </p>
            </a-layout-footer>
        </a-layout>
    </a-layout>
</template>


<script>
import {defineComponent, nextTick, onMounted, reactive, toRefs, watch} from "vue";
import {
    AppstoreOutlined, DownOutlined,
    MenuOutlined, PaperClipOutlined, ReadOutlined, SearchOutlined, StarFilled, StarOutlined,
    UnorderedListOutlined, UserOutlined
} from "@ant-design/icons-vue";
import globalVariable from "@/components/mathJax/globalVariable";
import {search} from "@/api/post/search";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";
import {logout as logout_request} from "@/api/post/logout";
import {login} from "@/api/post/login";
import {user_info} from "@/api/post/user_info";
import {notification} from "ant-design-vue";
import {favorite} from "@/api/post/favorite";
import {browsing} from "@/api/post/browsing";

export default defineComponent({
    components:{
        UserOutlined,
        DownOutlined,
        SearchOutlined,
        StarOutlined,
        StarFilled,
        ReadOutlined,
        PaperClipOutlined,
        MenuOutlined,
        AppstoreOutlined,
        UnorderedListOutlined,
    },
    setup(){

        // -------------onMounted钩子，组件挂载完毕异步加载数据--------------
        onMounted(() => {
            state.login = !store.state.logout;
            state.searchField = $route.query.searchField || 'title';
            state.searchQuery = $route.query.searchQuery || '';
            state.tagsChecked = $route.query.tagsChecked ? JSON.parse($route.query.tagsChecked) : [];
            // 调用搜索接口
            search(state.searchQuery, state.searchField, state.pageSize, state.currentPage, state.sort, state.tagsChecked, state.startDate, state.endDate).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    state.data = response.data.data.paperList;
                    state.total = response.data.data.total;
                    state.loading = false;
                }
            })
            checkLaTex()

            // 处理数据：用于设置悬停样式
            state.data.forEach((paper) => {
                // 区分Title，为每个paper设置单独的isTitleHovered属性
                paper.isTitleHovered = false;
                paper.authors.forEach((author) => {
                    // 区分author，为每个author设置单独的isHovered属性
                    author.isHovered = false;
                });
            });

        });

        // ----------------定义的function，由下至上编写---------------
        // 关键词高亮
        const highlightText = (text, keyword) => {
            // 使用正则表达式进行全局替换，忽略大小写
            const regex = new RegExp(keyword, 'gi');
            // 替换为带有样式的文本
            return text.replace(regex, '<span style="color: red;">$&</span>');
        }

        const onSearch = () => {
            state.loading = true;
            // 调用搜索接口
            search(state.searchQuery, state.searchField, state.pageSize, state.currentPage, state.sort, state.tagsChecked, state.startDate, state.endDate).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    state.data = response.data.data.paperList;
                    state.total = response.data.data.total;
                    // 处理数据：用于list显示
                    // 注意在回调函数中处理
                    if(state.paperShow==="list") {
                        let data2 = state.data.slice();
                        for (let i = 0; i < data2.length; i++) {
                            let author2String = "";
                            for (let j = 0; j < data2[i].authors.length; j++) {
                                author2String += data2[i].authors[j].author_name + "; ";
                                // 添加author字段，用于在list状态下显示
                                data2[i].author = author2String;
                            }
                        }
                        state.data = data2;
                    }
                    state.loading = false;
                }
            })

            // 处理数据：用于设置悬停样式
            state.data.forEach((paper) => {
                // 区分Title，为每个paper设置单独的isTitleHovered属性
                paper.isTitleHovered = false;
                paper.authors.forEach((author) => {
                    // 区分author，为每个author设置单独的isHovered属性
                    author.isHovered = false;
                });
            });
        }

        const handleFavorite = (paper_id) => {
            favorite(paper_id).then(() => {
                // 请求成功后，前端处理数据
                state.data.forEach((paper) => {
                    if (paper.paper_id === paper_id) {
                        paper.favorite = !paper.favorite;
                    }
                });
            });
        }

        const handleAuthor = (author_id) => {
            window.open('/author_show_demo?author_id=' + author_id, '_blank')
        }

        const handlePDF = (url) => {
            // 使用split方法按照'/'分割字符串，取得最后一个元素
            const parts = url.split("/");
            // 取得最后一个元素，即'0707.3421'
            const paper_id = parts[parts.length - 1];
            window.open('https://arxiv.org/pdf/' + paper_id + '.pdf', '_blank')
        }

        const handleRead = (paper_id) => {
            // 记录用户浏览论文历史
            browsing(paper_id).then((response) => {
                if(response.data.status.code === 0){
                    console.log("浏览埋点设置成功")
                }
            })
            window.open('/paper_show_demo?paper_id=' + paper_id, '_blank')
        }

        const onFinish = values => {
            login(values.username, values.password, values.remember).then((response) => {
                store.commit('CLEAR_USER_INFO')
                store.commit('CLEAR_TOKEN')
                if (response.data.status.code === 0) {
                    state.loginShow = false;
                    state.login = true;

                    store.commit('SET_LOGOUT', false)
                    //成功后继续请求用户信息
                    store.commit('SET_TOKEN', response.data.data)
                    console.log(response.data.data)
                    user_info()
                            .then((response) => {
                                if (response.data.status.code === 0) {
                                    // 成功后设置用户信息
                                    store.commit('SET_USER_INFO', response.data.data.user)
                                    console.log(response.data.data.user)
                                } else {
                                    notification['error']({
                                        message: '错误',
                                        description: response.data.status.message,
                                    })
                                }
                            })
                            .catch()
                } else if (response.data.status.code === 1 || response.data.status.code === 2) {
                    notification['warning']({
                        message: '登录失败',
                        description: '您提供的用户名或密码无效',
                    })
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })

        };

        const logout = () => {
            state.login = false;
            logout_request()
                    .then((response) => {
                        if (response.data) {
                            //退出成功
                            store.commit('SET_LOGOUT', true)
                            store.commit('CLEAR_USER_INFO')
                            store.commit('CLEAR_TOKEN')
                            // 清空本地存储的数据
                            sessionStorage.clear()
                            // 其他操作...
                        }
                    })
                    .catch(() => {
                        store.commit('SET_LOGOUT', true)
                        store.commit('CLEAR_USER_INFO')
                        store.commit('CLEAR_TOKEN')
                    })
        }

        const onMenuClick = ({ key }) => {
            switch (key) {
                case 'center': {
                    window.open('/user_center_demo', '_blank')
                    break
                }
                case 'favorite': {
                    window.open('/user_center_demo?currentKey=3&&selectedKeys=3&&openKeys=2', '_blank')
                    break
                }
                case 'interest': {
                    window.open('/user_center_demo?currentKey=4&&selectedKeys=4&&openKeys=2', '_blank')
                    break
                }
                case 'logout': {
                    logout()
                }
            }
        }

        const onLoginShow = () => {
            state.loginShow = true;
        };

        const onPaperShow = () => {
            state.paperShow = (state.paperShow==="card"?"list":"card");
            if(state.paperShow==="list"){
                // 处理数据
                let data2 = state.data.slice();
                for (let i = 0; i < data2.length; i++) {
                    let author2String = "";
                    for (let j = 0; j < data2[i].authors.length; j++) {
                        author2String += data2[i].authors[j].author_name + "; ";
                        // 添加author字段，用于在list状态下显示
                        data2[i].author = author2String;
                    }
                }
                state.data = data2;
            }
        };

        const onShowSizeChange = (current, pageSize) => {
            state.loading = true;
            // 调用搜索接口
            search(state.searchQuery, state.searchField, pageSize, current, state.sort, state.tagsChecked, state.startDate, state.endDate).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    state.pageSize = pageSize;
                    state.currentPage = current;
                    state.data = response.data.data.paperList;
                    state.total = response.data.data.total;
                    if(state.paperShow==="list"){
                        // 处理数据
                        let data2 = state.data.slice();
                        for (let i = 0; i < data2.length; i++) {
                            let author2String = "";
                            for (let j = 0; j < data2[i].authors.length; j++) {
                                author2String += data2[i].authors[j].author_name + "; ";
                                data2[i].author = author2String;
                            }
                        }
                        state.data = data2;
                    }
                    state.loading = false;
                }
            })
        }

        const onPageChange = pageNumber => {
            state.loading = true;
            // 调用搜索接口
            search(state.searchQuery, state.searchField, state.pageSize, pageNumber, state.sort, state.tagsChecked, state.startDate, state.endDate).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    state.currentPage = pageNumber;
                    state.data = response.data.data.paperList;
                    state.total = response.data.data.total;
                    if(state.paperShow==="list"){
                        // 处理数据
                        let data2 = state.data.slice();
                        for (let i = 0; i < data2.length; i++) {
                            let author2String = "";
                            for (let j = 0; j < data2[i].authors.length; j++) {
                                author2String += data2[i].authors[j].author_name + "; ";
                                data2[i].author = author2String;
                            }
                        }
                        state.data = data2;
                    }
                    window.scroll({
                        top: 0,
                        behavior: 'smooth' // 使用平滑滚动
                    });
                    state.loading = false;
                }
            })
        }

        const checkLaTex = () => {
            globalVariable.initMathjaxConfig();
            globalVariable.MathQueue();
        }

        // --------------------定义的vue变量------------------------
        // 确保在使用 '$route' 之前已经声明并初始化了它
        const router = useRouter()
        const $route = useRoute();
        const store = useStore()

        // --------------------定义的响应数据-----------------------
        const state = reactive({
            loginShow: false,
            paperShow: "card",
            login: true,
            pageSize: 10,
            total: 0,
            currentPage: 1,
            ellipsis: true,
            startDate: '',
            endDate: '',
            tagsChecked: [],            //标签筛选首页中呈现的已经选中的标签
            sort:"time",
            data:[],
            loading: true,
            searchOptions: [
                { label: '标题', value: 'title' },
                { label: '摘要', value: 'abstract' },
                { label: '作者', value: 'author' },
                { label: '期刊', value: 'journal' },
            ],
            searchQuery: '',
            searchField: 'title',
            backGroundImg: require('@/assets/background2.png'),
        })

        const formState = reactive({
            username: '',
            password: '',
            remember: false,
        });

        // ----------------------定义的常量--------------------
        const columns = [{
            title: '题名',
            dataIndex: 'title',
            width: 480,
        }, {
            title: '作者',
            dataIndex: 'author',
            width: 200,
        }, {
            title: '发表期刊',
            dataIndex: 'journal_ref',
            width: 200,
        }, {
            title:'更新时间',
            dataIndex: 'update_date',
            width: 120,
        }, {
            title: '操作',
            dataIndex: 'operations',
            width: 100,
        }];

        // ----------------------return函数-------------------
        return{
            highlightText,
            onSearch,
            handleFavorite,
            handleAuthor,
            handlePDF,
            handleRead,
            onFinish,
            formState,
            onMenuClick,
            onLoginShow,
            columns,
            onPaperShow,
            onShowSizeChange,
            onPageChange,
            ...toRefs(state),
            systemTitle: process.env.VUE_APP_TITLE,
        }
    }
})
</script>

<style scoped>

.active {
    background-color: #4F4F4F;
    color: white;
}
.inactive {
    background-color: white;
    color: #4F4F4F;
}

/*分割线*/
.custom-divider {
    border: none;
    height: 1px;
    background-color: #BBBBBB;
}
</style>